<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row v-show="showSearch">
        <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
          <el-form-item label="证书名称" prop="certificateName" style="width: 220px">
            <el-select filterable v-model="state.queryForm.certificateTemplateName" placeholder="请选择证书名称">
              <el-option :label="item.certificateTemplateName" :value="item.certificateTemplateName"
                v-for="(item, index) in certificate_name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工姓名" prop="username" style="width: 220px">
            <!--            <el-select v-model="state.queryForm.username" placeholder="请选择员工姓名">-->
            <!--              <el-option label="请选择">0</el-option>-->
            <!--            </el-select>-->
            <el-input v-model="state.queryForm.username" placeholder="请输入员工姓名" />
          </el-form-item>
          <el-form-item label="岗位名称" prop="postName" style="width: 220px">
            <!--            <el-select v-model="state.queryForm.postName" placeholder="请选择岗位名称">-->
            <!--              <el-option label="请选择">0</el-option>-->
            <!--            </el-select>-->
            <el-input v-model="state.queryForm.postName" placeholder="请输入岗位名称" />
          </el-form-item>
          <el-form-item label="证书类型" prop="certificateType" style="width: 220px">
            <el-select v-model="state.queryForm.certificateType" placeholder="请选择证书类型">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in certificate_type"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证书性质" prop="certificateNature" style="width: 220px">
            <el-select v-model="state.queryForm.certificateNature" placeholder="请选择证书性质">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in certificate_nature"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="颁发机构" prop="authority" style="width: 220px">
            <el-select v-model="state.queryForm.authority" placeholder="请选择颁发机构">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in certification_authority"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">
              查询
            </el-button>
            <!--            <el-button icon="Refresh" @click="resetQuery">重置</el-button>-->
            <el-button plain :disabled="multiple" icon="Delete" type="danger"
              v-auth="'train_zsglCertificateQualifications_del'" @click="handleDelete(selectObjs)">
              删除
            </el-button>
            <el-button icon="Plus" type="danger" @click="uploadModule">
              个人证书上传
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <!--      <el-row>-->
      <!--        <div class="mb8" style="width: 100%">-->
      <!--          <el-button icon="folder-add" type="primary" class="ml10" @click="formDialogRef.openDialog()"-->
      <!--            v-auth="'train_zsglCertificateQualifications_add'">-->
      <!--            新 增-->
      <!--          </el-button>-->
      <!--          <right-toolbar v-model:showSearch="showSearch" :export="'train_zsglCertificateQualifications_export'"-->
      <!--                @exportExcel="exportExcel" class="ml10 mr20" style="float: right;"-->
      <!--            @queryTable="getDataList"></right-toolbar>-->
      <!--        </div>-->
      <!--      </el-row>-->
      <el-table :data="state.dataList" v-loading="state.loading" border :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle" @selection-change="selectionChangHandle"
        @sort-change="sortChangeHandle">
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="certificateName" label="证书名称" show-overflow-tooltip />
        <el-table-column prop="username" label="员工姓名" show-overflow-tooltip />
        <el-table-column prop="usercode" label="人员编码" show-overflow-tooltip />
        <el-table-column prop="postName" label="岗位名称" show-overflow-tooltip />
        <el-table-column prop="isTripartiteCertificate" label="是否为三方证书" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="primary">{{ scope.row.isTripartiteCertificate == 1 ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="certificateType" label="证书类型" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="certificate_type" :value="scope.row.certificateType"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="certificateNature" label="证书性质" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="certificate_nature" :value="scope.row.certificateNature"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="authority" label="颁发机构" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="certification_authority" :value="scope.row.authority"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" show-overflow-tooltip />
        <el-table-column prop="endDate" label="结束日期" show-overflow-tooltip />
        <el-table-column prop="auditStatus" label="审核状态" show-overflow-tooltip>
          <template #default="scope">
            <div v-if="scope.row.auditStatus == 0 || scope.row.auditStatus == 1 || scope.row.auditStatus == 2">
              <el-tag @click="ceshi1(scope.row)" type="primary">{{ scope.row.auditStatus == 0 ? '未通过' :
                scope.row.auditStatus == 1 ? '审核中' : scope.row.auditStatus == 2 ? '已完成' : '' }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="issuanceDate" label="发证时间" show-overflow-tooltip>
          <template #default="scope">
            <el-tag type="primary">{{ scope.row.issuanceDate }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button v-if="scope.row.isTripartiteCertificate == 1" icon="edit-pen" text type="primary"
              v-auth="'train_zsglCertificateQualifications_edit'" @click="uploadModule(scope.row.id)">编辑</el-button>
            <el-button icon="edit-pen" text type="primary" v-auth="'train_zsglCertificateQualifications_edit'"
              @click="openPreview(scope.row, scope.row.isTripartiteCertificate)">{{ scope.row.isTripartiteCertificate ==
                1 ? '下载' : '预览' }}</el-button>
            <!--            <el-button icon="delete" text type="primary" v-auth="'train_zsglCertificateTemplate_del'" @click="handlepreivew(scope.row)"-->
            <!--            >预览</el-button>-->
            <el-button icon="delete" text type="primary" v-auth="'train_zsglCertificateQualifications_del'"
              @click="handleDelete([scope.row.id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    </div>
    <!-- 编辑、新增  -->
    <form-dialog ref="formDialogRef" @refresh="getDataList(false)" />
    <!--预览-->
    <el-dialog v-model="dialogTableVisible" width="1000" style="text-align: center">
      <el-image v-loading="loading" style="width: 800px; height: 600px" :src="mapSrc" :fit="fit" />
    </el-dialog>
    <!-- 证书上传-->
    <el-dialog :title="form.id ? '修改员工证书资质' : '新增员工证书资质'" v-model="dialoguploadModule" width="1000"
      :close-on-click-modal="false" draggable>
      <div style="display: flex;align-items: center;position: relative;height: 100%">
        <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px">
          <el-form-item label="证书名称" prop="certificateName">
            <el-input v-model="form.certificateName" placeholder="请选择证书名称" />
          </el-form-item>
          <el-form-item label="证书类型" prop="certificateType">
            <el-select @change="typechange" filterable v-model="form.certificateTypes" placeholder="请选择证书类型">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in certificate_type"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工工号" prop="usercode">

            <el-input v-model="form.usercode" placeholder="请输入员工工号"></el-input>
          </el-form-item>
          <el-form-item label="员工姓名" prop="username">
            <el-input v-model="form.username" placeholder="请输入员工姓名"></el-input>
          </el-form-item>
          <el-form-item label="证书性质" prop="certificateNature">
            <el-select @change="naturechange" filterable v-model="form.certificateNatures" placeholder="请选择证书性质">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in certificate_nature"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item filterable label="颁发机构" prop="authority">
            <el-select @change="authchange" filterable v-model="form.authoritys" placeholder="请选择颁发机构">
              <el-option :label="item.label" :value="item.value" v-for="(item, index) in certification_authority"
                :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="display: flex;flex-direction: column" label-width="0">
            <el-row :span="4" class="mb20">
              <el-form-item label="永久有效" prop="isPermanent" required style="margin-left: 0">
                <el-switch v-model="form.isPermanent" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-row>

            <div style="display: flex">
              <el-col :span="12" class="mb20" v-if="form.isPermanent === 0">
                <el-form-item label=" " prop="startDate">
                  <el-date-picker format="YYYY/MM/DD" value-format="YYYY-MM-DD" @change="startchange"
                    v-model="form.startDate" type="date" label="Pick a date" placeholder="有效期开始时间"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12" class="mb20" v-if="form.isPermanent === 0">
                <el-form-item label=" " prop="endDate">
                  <el-date-picker format="YYYY/MM/DD" v-model="form.endDate" value-format="YYYY-MM-DD" type="date"
                    @change="endDatechange" label="Pick a date" placeholder="有效期结束时间" style="width: 100%" />
                </el-form-item>
              </el-col>
            </div>


          </el-form-item>
          <el-form-item style="display: flex;flex-direction: column" prop="fileModule" label-width="0">
            <div style="display: flex;">
              <el-upload ref="uploadppt" limit="1" accept=".png,.jpg" class="upload-demo"
                :action="actionUrl + '/uploadFile'" :on-success="uploadSuccess" style="width: 600px"
                :before-remove="removeFile(0)" :before-upload="uploadbefore">
                <el-button plane>
                  <!--							<el-icon><Download /></el-icon>-->
                  <svg t="1712807276206" class="icon" viewBox="0 0 1024 1024" version="1.1"
                    xmlns="http://www.w3.org/2000/svg" p-id="1192" width="200" height="200">
                    <path
                      d="M659.626667 780.8h-298.666667c-104.106667 0-189.44-85.333333-189.44-189.44 0-91.306667 63.146667-167.253333 150.186667-185.173333 9.386667-95.573333 90.453333-170.666667 188.586666-170.666667s179.2 75.093333 188.586667 170.666667c87.04 17.92 150.186667 93.866667 150.186667 185.173333 0 104.106667-85.333333 189.44-189.44 189.44zM510.293333 286.72c-75.946667 0-138.24 62.293333-138.24 138.24v26.453333l-23.04 1.706667c-71.68 5.973333-126.293333 65.706667-126.293333 137.386667 0 75.946667 62.293333 138.24 138.24 138.24h298.666667c75.946667 0 138.24-62.293333 138.24-138.24 0-72.533333-53.76-131.413333-126.293334-137.386667l-23.04-1.706667v-26.453333c0-76.8-62.293333-138.24-138.24-138.24z"
                      fill="#190D04" p-id="1193"></path>
                    <path
                      d="M584.533333 550.4c-7.68 0-14.506667-3.413333-19.626666-9.386667l-45.226667-56.32c-2.56-2.56-5.12-3.413333-5.973333-3.413333-1.706667 0-4.266667 0-6.826667 2.56l-52.053333 57.173333c-9.386667 10.24-25.6 11.093333-35.84 1.706667s-11.093333-25.6-1.706667-35.84l52.053333-57.173333c11.946667-12.8 28.16-19.626667 46.08-19.626667 17.066667 0.853333 34.133333 8.533333 44.373334 22.186667l45.226666 56.32c8.533333 11.093333 7.68 27.306667-3.413333 35.84-5.12 4.266667-11.093333 5.973333-17.066667 5.973333z"
                      fill="#E56D1C" p-id="1194"></path>
                    <path
                      d="M510.293333 651.946667c-14.506667 0-25.6-11.093333-25.6-25.6V459.946667c0-14.506667 11.093333-25.6 25.6-25.6s25.6 11.093333 25.6 25.6v167.253333c0 13.653333-11.946667 24.746667-25.6 24.746667z"
                      fill="#E56D1C" p-id="1195"></path>
                  </svg>上传正面证书
                </el-button>
                <div class="el-upload__tip" style="margin-left: 15px"><i
                    style="color: red;margin-right: 10px">*</i>支持扩展名：.png,.jpg 且不超过3MB</div>
              </el-upload>
              <div v-if="isdownload" style="width: 50%;">
                <span style="padding-right: 15px; ">{{ templateName }}</span>
                <!--                <el-button @click="preview">模版预览</el-button>-->
                <el-button @click="downloadTemplate">模版下载</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label-width="0">
            <el-upload ref="uploadpng" limit="1" accept=".png" class="upload-demo" :action="actionUrl + '/uploadFile'"
              :on-success="uploadSuccessicon" :before-upload="uploadbeforeicon" :before-remove="removeFile(1)"
              style="width: 600px">
              <el-button plane>
                <svg t="1712807276206" class="icon" viewBox="0 0 1024 1024" version="1.1"
                  xmlns="http://www.w3.org/2000/svg" p-id="1192" width="200" height="200">
                  <path
                    d="M659.626667 780.8h-298.666667c-104.106667 0-189.44-85.333333-189.44-189.44 0-91.306667 63.146667-167.253333 150.186667-185.173333 9.386667-95.573333 90.453333-170.666667 188.586666-170.666667s179.2 75.093333 188.586667 170.666667c87.04 17.92 150.186667 93.866667 150.186667 185.173333 0 104.106667-85.333333 189.44-189.44 189.44zM510.293333 286.72c-75.946667 0-138.24 62.293333-138.24 138.24v26.453333l-23.04 1.706667c-71.68 5.973333-126.293333 65.706667-126.293333 137.386667 0 75.946667 62.293333 138.24 138.24 138.24h298.666667c75.946667 0 138.24-62.293333 138.24-138.24 0-72.533333-53.76-131.413333-126.293334-137.386667l-23.04-1.706667v-26.453333c0-76.8-62.293333-138.24-138.24-138.24z"
                    fill="#190D04" p-id="1193"></path>
                  <path
                    d="M584.533333 550.4c-7.68 0-14.506667-3.413333-19.626666-9.386667l-45.226667-56.32c-2.56-2.56-5.12-3.413333-5.973333-3.413333-1.706667 0-4.266667 0-6.826667 2.56l-52.053333 57.173333c-9.386667 10.24-25.6 11.093333-35.84 1.706667s-11.093333-25.6-1.706667-35.84l52.053333-57.173333c11.946667-12.8 28.16-19.626667 46.08-19.626667 17.066667 0.853333 34.133333 8.533333 44.373334 22.186667l45.226666 56.32c8.533333 11.093333 7.68 27.306667-3.413333 35.84-5.12 4.266667-11.093333 5.973333-17.066667 5.973333z"
                    fill="#E56D1C" p-id="1194"></path>
                  <path
                    d="M510.293333 651.946667c-14.506667 0-25.6-11.093333-25.6-25.6V459.946667c0-14.506667 11.093333-25.6 25.6-25.6s25.6 11.093333 25.6 25.6v167.253333c0 13.653333-11.946667 24.746667-25.6 24.746667z"
                    fill="#E56D1C" p-id="1195"></path>
                </svg>上传图标
              </el-button>
              <div class="el-upload__tip" style="margin-left: 15px">支持扩展名：.png 且不超过200kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <!--				<el-button @click="visible = false">取消</el-button>-->
          <el-button type="primary" @click="onSubmit" :disabled="loadingadd"
            style="width: 150px; height: 40px">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemZsglCertificateQualifications">
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList, delObjs, getObj, addObj2, putObj } from "/@/api/train/zsglCertificateQualifications";
import { useMessage, useMessageBox } from "/@/hooks/message";
import { useDict } from '/@/hooks/dict';
import { getcertificateName, getCertificatePreview } from "/@/api/train/zsglCertificateTemplate";
import { office, officeView } from "/@/api/train/kszlFile";
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义查询字典
const { certification_authority, certificate_nature, certificate_type } = useDict('certification_authority', 'certificate_nature', 'certificate_type')
// 定义变量内容
const formDialogRef = ref()
// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
const dialogTableVisible = ref(false)
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})

const ceshi1 = (e: any) => {
  console.log(e)
}

// 上传ref
const uploadppt = ref<UploadInstance>()
const uploadpng = ref<UploadInstance>();
// 加载组件开启
const loading = ref(true)
// 证书名称
const certificate_name = ref([]);
// 获取证书名称
onMounted(() => {
  getName();
  office().then((res) => {
    actionUrl.value = res.data;
  });
  officeView().then(res => {
    actionUrl1.value = res.data
  })
});
// pptx预览dom
const xmlread = ref()
// 获取证书名称
const getName = async () => {
  const res = await getcertificateName();
  console.log(res);
  certificate_name.value = res;
};

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  downBlobFile,
  tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}

const mapSrc: string = ref();

// 证书预览
const openPreview = async (row: any, index?: number) => {
  if (index) {
    // 获取文件的唯一id
    templateId.value = row.fileUid
    const baseUrl = '/downloadFile/'
    window.open(
      actionUrl.value + baseUrl + templateId.value
    )
    return
  }
  console.log(row)
  mapSrc.value = ''
  dialogTableVisible.value = true
  const res = await getCertificatePreview(row.certificateId)
  const btoa1 = btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
  mapSrc.value = `data:image/png;base64,${btoa1}`
  loading.value = false


}

// 导出excel
const exportExcel = () => {
  downBlobFile('/train/zsglCertificateQualifications/export', Object.assign(state.queryForm, { ids: selectObjs }), 'zsglCertificateQualifications.xlsx')
}

// 多选事件
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => id);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm('此操作将永久删除');
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success('删除成功');
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};



//  个人模板上传
// 打开新增页面
const dialoguploadModule = ref(false)
// 证书添加
const loadingadd = ref(false)
// 表单校验ref
const dataFormRef = ref()
// 提交表单数据
const form = reactive({
  id: '',
  certificateTemplateId: '',
  certificateTemplateName: '',
  certificateType: '',
  certificateNature: '',
  authority: '',
  isPermanent: 1,
  startDate: '',
  endDate: '',
  remark: '',
  fileName: '',
  fileNameAll: '',
  fileNameView: '',
  fileAddress: '',
  fileSize: '',
  filePage: '',
  fileUid: '',
  photoName: '',
  photoNameAll: '',
  photoNameView: '',
  photoAddress: '',
  photoSize: '',
  photoUid: '',
  createBy: '',
  createTime: '',
  updateBy: '',
  updateTime: '',
  isPermanents: true,
  certificateTypes: '',
  authoritys: '',
  certificateNatures: '',
  time_valid: 1,
  time_valids: true,
  usercode: '',
  username: '',
  certificateName: '',
  auditStatus: 1,
  isTripartiteCertificate: 1,
})

// 重置表单数据
const formreset = {
  certificateName: '',
  usercode: '',
  username: '',
  certificateTemplateId: '',
  certificateTemplateName: '',
  certificateType: '',
  certificateNature: '',
  authority: '',
  isPermanent: 1,
  startDate: '',
  endDate: '',
  remark: '',
  fileName: '',
  fileNameAll: '',
  fileNameView: '',
  fileAddress: '',
  fileSize: '',
  filePage: '',
  fileUid: '',
  photoName: '',
  photoNameAll: '',
  photoNameView: '',
  photoAddress: '',
  photoSize: '',
  photoUid: '',
  createBy: '',
  createTime: '',
  updateBy: '',
  updateTime: '',
  isPermanents: true,
  certificateTypes: '',
  authoritys: '',
  certificateNatures: '',
  time_valid: 1,
  time_valids: true,
  id: '',
}
// 定义校验规则
const dataRules = reactive<FormRules<RuleForm>>({
  certificateName: [{ required: true, message: '请输入证书名称', trigger: 'blur' }],
  certificateType: [{ required: true, message: '请选择证书类型', trigger: 'blur', },],
  certificateNature: [{ required: true, message: '请选择证书性质', trigger: 'blur' }],
  authority: [{ required: true, message: '请选择颁发机构', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  endDate: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
  usercode: [{ required: true, message: '请输入员工工号', trigger: 'blur' },
  { pattern: /^[0-9]*$/, message: '工号需为数字', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名称', trigger: 'blur' }],
});

// 获取当前的时间
const getCurrentTime = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

// 删除文件清空表单
const removeFile = (index: number) => {
  if (index == 0) {
    Object.assign(form, {
      fileName: '',
      fileNameAll: '',
      fileNameView: '',
      fileAddress: '',
      fileSize: '',
      filePage: '',
      fileUid: '',
    })
  }
  Object.assign(form, {
    photoName: '',
    photoNameAll: '',
    photoNameView: '',
    photoAddress: '',
    photoSize: '',
    photoUid: '',
  })
}

// 后台请求路径
const actionUrl = ref();
// 文件预览路径
const actionUrl1 = ref()
// 类型改变
const typechange = (val: any) => {
  console.log(val)
  console.log(certificate_type.value[val].label)
}
const authchange = (val: any) => {
  console.log(certification_authority.value[val].label)
}
// 有效期时间控制改变


// 有效期判定时间
const switchChange = () => {
  if (form.isPermanent) {
    isopend.value = false
    form.isPermanent = 1;
    istimeswitch.value = true;
    form.startDate = '2000-12-12';
    form.endDate = '2099-12-12';
    return;
  }
  isopend.value = true
  istimeswitch.value = false;
  form.startDate = '';
  form.endDate = '';
  form.isPermanent = 0;
};
// 时间控制开关
const isopend = ref(false)
// 时间禁用开关
const istimeswitch = ref(false);
// 提交用法
const onSubmit = async () => {
  if (form.fileNameAll || photonum.value) {
    if (form.fileSize / 1024 / 1024 >= 3) {
      useMessage().error('文件大小不应该超过3M')
      uploadppt.value.clearFiles()
      form.fileSize = 0
      Object.assign(form, {
        fileName: '',
        fileNameAll: '',
        fileNameView: '',
        fileAddress: '',
        fileSize: '',
        filePage: '',
        fileUid: '',
      })
      return
    }
  }
  if (form.photoSize) {
    if (form.photoSize / 1024 / 200 >= 1) {
      useMessage().error('图片大小不应该超过200KB')
      uploadpng.value.clearFiles()
      Object.assign(form, {
        photoName: '',
        photoNameAll: '',
        photoNameView: '',
        photoAddress: '',
        photoSize: '',
        photoUid: '',
      })
      return
    }
  }
  form.authority = parseInt(form.authoritys);
  form.certificateNature = parseInt(form.certificateNatures);
  form.certificateType = parseInt(form.certificateTypes);
  // form.issuanceDate = getCurrentTime()
  console.log(form)
  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;

  try {
    loadingadd.value = true;
    form.id ? await putObj(form) : await addObj2(form);
    uploadppt.value.clearFiles()
    uploadpng.value.clearFiles()
    useMessage().success(form.id ? '修改成功' : '添加成功');
    dialoguploadModule.value = false;
    getDataList()
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loadingadd.value = false;
  }
};

// 判断是否显示模板预览
const isdownload = ref(false)
// 获取模版名称
const templateName = ref()
// 预览链接地址
const allurl = ref()
// 模版预览
const preview = () => {
  window.open(allurl.value)
}
// 模板id
const templateId = ref()

// 模版下载
const downloadTemplate = () => {
  const baseUrl = '/downloadFile/'
  window.open(
    actionUrl.value + baseUrl + templateId.value
  )
}
// 打开弹窗
const uploadModule = (id: string) => {

  isopend.value = false
  // form.isPermanents = true
  dialoguploadModule.value = true;
  form.id = '';
  isdownload.value = false
  istimeswitch.value = false

  // 重置表单数据
  nextTick(() => {
    Object.assign(form, formreset)
  });
  if (id) {
    form.id = id;
    // 判断状态 是否显示预览按钮
    // isdownload.value = true
    getzsglCertificateTemplateData(id);
  }
}
// 获取文件大小
const photonum = ref()
// 判断编辑页面
const getzsglCertificateTemplateData = (id: string) => {
  // 获取数据
  dialoguploadModule.value = true;
  getObj(id)
    .then((res: any) => {
      console.log(res)
      Object.assign(form, res.data)
      isdownload.value = true
      form.certificateNatures = certificate_nature.value[form.certificateNature].label
      form.certificateTypes = certificate_type.value[form.certificateType].label
      form.authoritys = certification_authority.value[form.authority].label
      photonum.value = res.data.fileNameAll
      // 获取文件的唯一id
      templateId.value = form.fileUid
      // 获取文件名全称
      templateName.value = form.fileNameAll
      console.log(form)
      // 判断编辑时 时间按钮的状态
      form.isPermanents = form.isPermanent === 1
      // 给禁用变量赋值
      if (form.isPermanents) {
        istimeswitch.value = true
      } else {
        isopend.value = true
      }
      let originalUrl = `${actionUrl.value}/downloadFilec?id=${form.fileUid}`;
      let previewUrl = originalUrl + `&fullfilename=${form.fileUid}.${form.fileName}`
      //转换为 Base64 编码
      let base64EncodedUrl = btoa(previewUrl);
      //使用 encodeURIComponent 编码
      let encodedUrl = encodeURIComponent(base64EncodedUrl);
      allurl.value = actionUrl1.value + encodedUrl
    })
    .finally(() => {
      loading.value = false;
    });
};

// 时间校验函数
const startchange = () => {
  if (form.startDate && form.endDate && form.startDate > form.endDate) {
    form.startDate = ''
    useMessage().error('开始时间不能大于结束时间')
  }
}
const endDatechange = () => {
  if (form.endDate && form.endDate < form.startDate) {
    form.endDate = ''
    useMessage().error('结束时间不能小于开始时间')
  }
}

const uploadSuccessicon = (val: any) => {
  form.photoName = val.data.suffix;
  form.photoNameAll = val.data.title;
  form.photoNameView = val.data.name;
  form.photoAddress = val.data.url;
  form.photoSize = val.data.size;
  form.photoUid = val.data.id;
};

const uploadSuccess = (val: any) => {
  console.log(val, 1111111111111)
  form.fileName = val.data.suffix;
  form.fileNameAll = val.data.title;
  form.fileNameView = val.data.name;
  form.fileAddress = val.data.url;
  form.fileSize = val.data.size;
  form.fileUid = val.data.id;
};

</script>
<style scoped>
.el-form-item__content {
  margin-left: 0 !important;
}

.mr0 .el-form-item__content {

  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.el-dialog__footer {
  text-align: center !important;
}

.icon {
  width: 20px;
  height: 20px;
}
</style>
